#include "favoritehubsaver.h"
#include <QVariant>
#include "dcpp/FavoriteManager.h"
#include "globaldefinition.h"

using namespace FavHubModif;
using namespace dcpp;

FavoriteHubModifer::FavoriteHubModifer(QObject *parent) :
    QObject(parent)
{
}

void FavoriteHubModifer::add(const QString &URL, const QString &name, const QString &value){
    m_hubsparam[URL][name] = value;
}

/** Заполнить описание любимого хаба
 *
 * @param param Перечислитель параметров для заполнения описания любимого хаба.
 * @param entry Указатель на описание хаба, которое набо заполнить.
 */
void writeInFavoriteHubEntry(ParamIterator param, FavoriteHubEntryPtr entry){
    while (param.hasNext()) {
        param.next();
        qDebug()<<Q_FUNC_INFO<<__LINE__<<param.key()<<param.value();
        if(param.key() == userdescription)
            entry->setUserDescription(_tq(param.value()));
        if(param.key() == name)
            entry->setName(_tq(param.value()));
        if(param.key() == server)
            entry->setServer(_tq(param.value()));
        if(param.key() == description)
            entry->setDescription(_tq(param.value()));
        if(param.key() == password)
            entry->setPassword(_tq(param.value()));
        if(param.key() == encoding)
            entry->setEncoding(_tq(param.value()));
        if(param.key() == group)
            entry->setGroup(_tq(param.value()));
        if(param.key() == nick)
            entry->setNick(_tq(param.value()));
    }
}

void FavoriteHubModifer::save(const QString &URL){
    qDebug()<<Q_FUNC_INFO<<__LINE__<<URL;
    auto oldEntry = FavoriteManager::getInstance()->getFavoriteHubEntry(_tq(URL));
    FavoriteHubEntry * entry = nullptr;
    if(oldEntry){
        entry = new FavoriteHubEntry(*oldEntry);
        FavoriteManager::getInstance()->removeFavorite(oldEntry);
    }
    else
        entry = new FavoriteHubEntry();

    ParamIterator param(m_hubsparam[URL]);
    writeInFavoriteHubEntry(param, entry);

    FavoriteManager::getInstance()->addFavorite(*entry);
    delete entry;
}
